package com.dmall.graph.floodfill;

/**
 * @author xiao1.wang
 * @date 2020-06-05 12:26:00
 */
public class Leetcode827V1 {
    private int R, C;
    private int[][] grid;
    private int[][] visited;
    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public int largestIsland(int[][] grid) {
        R = grid.length;
        C = grid[0].length;

        this.grid = grid;

        visited = new int[R][C];
        int max = 0;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (grid[i][j] == 0) {
                    grid[i][j] = 1;
                    max = Math.max(max, largestIsland());
                    this.visited = new int[R][C];
                    grid[i][j] = 0;
                }
            }
        }
        if (max == 0) {
            // 表示所有的都是1，这种直接返回网格的数量
            max = R * C;
        }
        return max;
    }

    private int largestIsland() {
        int res = 0;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (visited[i][j] == 0 && grid[i][j] == 1) {
                    res = Math.max(res, dfs(i, j));
                }
            }
        }

        return res;
    }

    private int dfs(int x, int y) {
        int res = 1;
        visited[x][y] = 1;
        for (int i = 0; i < dirs.length; i++) {
            int nextx = x + dirs[i][0];
            int nexty = y + dirs[i][1];
            if (inArea(nextx, nexty) && visited[nextx][nexty] == 0 && grid[nextx][nexty] == 1) {
                res += dfs(nextx, nexty);
            }
        }
        return res;
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        int[][] grid = {{1, 1}, {1, 1}};
        // int[][] grid = {{1, 1, 1, 1, 0}, {1, 0, 0, 0, 0}, {0, 0, 0, 1, 1}, {1, 1, 0, 1, 0}, {0, 0, 0, 0, 1}};
        Leetcode827V1 leetcode827 = new Leetcode827V1();
        int res = leetcode827.largestIsland(grid);
        System.out.println(res);
    }
}
